/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[欢迎加盟知启蒙，一起邂逅框架梦]
 * 
 * https://www.zhiqim.com/gitcan/zhiqim/zhiqim_account.htm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.zhiqim.account.action.connect;

import org.zhiqim.account.ZacConstants;
import org.zhiqim.account.ZacSessionUser;
import org.zhiqim.account.api.connect.WxService;
import org.zhiqim.account.api.connect.WxUserInfo;
import org.zhiqim.account.dbo.user.UserAccount;
import org.zhiqim.account.dbo.user.UserInfo;
import org.zhiqim.account.presenter.UserPassportPresenter;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.core.Action;
import org.zhiqim.kernel.Global;
import org.zhiqim.kernel.httpclient.HttpResult;
import org.zhiqim.kernel.json.Jsons;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ZTable;

/**
 * 微信开放平台第三方登陆回调
 * https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&lang=zh_CN
 *
 * @version v1.0.0 @author yangpeng 2018-1-26 新建与整理
 */
public class WxopCallbackAction implements Action, ZacConstants
{
    @Override
    public void execute(HttpRequest request) throws Exception
    {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        
        if(Validates.isEmpty(code))
        {//用户禁止授权
            request.getResponse().sendRedirect("/index.htm");
            return;
        }
        
        if (!ZAC_NAME.equals(state))
        {//如果是没有state表示不是从系统进入
            request.getResponse().sendRedirect("/index.htm");
            return;
        }

        HttpResult result = WxService.getAccessTokenByOpen(code);
        if(!result.isSuccess())
        {//获取access_token失败
            request.setRedirect("/index.htm", result.getResponseText());
            return;
        }
        
        String responseText = result.getResponseText();
        String openid = Jsons.getString(responseText, "openid");
        String accessToken = Jsons.getString(responseText, "access_token");
        
        result = WxService.getUserInfo(accessToken, openid);
        if(!result.isSuccess())
        {//获取用户信息失败
            request.setRedirect("/index.htm", result.getResponseText());
            return;
        }
        
        //登录并跳转
        WxUserInfo userInfo = new WxUserInfo().parse(result.getResponseText()).setAccountType(ACCOUNT_TYPE_WXOP);
        
        if (request.hasSessionUser(ZacSessionUser.class))
        {//执行绑定操作
            UserPassportPresenter.bindByConnect(request, userInfo);
        }
        else
        {//跳转注册或者登录页面
            UserPassportPresenter.loginByConnect(request, userInfo);
            UserAccount account = Global.get(ZTable.class).item(UserAccount.class, userInfo.getUserAccount());
            if (account != null)
            {
                UserInfo user = Global.get(ZTable.class).item(UserInfo.class, account.getUserId());
                if (user != null && Validates.isNotEmpty(user.getUserName()))
                {//用户名不为空允许跳转登录
                    request.setRedirect(Strings.trimLeft(request.getRequestURI(), request.getRootPath("/connect/wxopcallback")));
                }
            }
        }
    }
}
